package net.qhzw.vip.qiyu.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.qhzw.vip.qiyu.component.ServerConfig;
import net.qhzw.vip.qiyu.constant.SysConstants;
import net.qhzw.vip.qiyu.entity.*;
import net.qhzw.vip.qiyu.handler.MyException;
import net.qhzw.vip.qiyu.mapper.ContractMapper;
import net.qhzw.vip.qiyu.mapper.DtsBatteryHistoryMapper;
import net.qhzw.vip.qiyu.mapper.DtsBatteryManageMapper;
import net.qhzw.vip.qiyu.model.*;
import net.qhzw.vip.qiyu.service.*;
import net.qhzw.vip.qiyu.util.BeanMapUtils;
import net.qhzw.vip.qiyu.util.MyDateUtils;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DtsBatteryManageImpl extends ServiceImpl<DtsBatteryManageMapper, DtsBatteryManage> implements DtsBatteryManageService {

     @Autowired
     DtsBatteryManageMapper dtsBatteryManageMapper;
     @Autowired
   private DtsBatteryHistoryMapper dtsBatteryHistoryMapper;

    @Override
    public Map<String, Object> findByPage(Page<DtsBatteryManage> page,String electricCabinetCode, Long batteryStatus,String electricCabinetName,
                                          String batteryCode) {
        Map<String, Object> result = new HashMap<>();
        PageHelper.startPage((int) page.getCurrent(), (int) page.getSize());
        List<DtsBatteryManage> dtsBatteryManageList = dtsBatteryManageMapper.findByPage(electricCabinetCode,batteryStatus,electricCabinetName,batteryCode);
        PageInfo<DtsBatteryManage> pageInfo = new PageInfo<>(dtsBatteryManageList);
        result.put("total", (int) pageInfo.getTotal());
        result.put("records", pageInfo.getList());
        return result;

        //return page(page, new LambdaQueryWrapper<DtsBatteryManage>()
        //        .eq( DtsBatteryManage::getIsDelete, 0)
        //        .like(dtsBatteryManage != null && !StringUtils.isEmpty(dtsBatteryManage.getElectricCabinetName()),DtsBatteryManage::getElectricCabinetName,dtsBatteryManage.getElectricCabinetName())
        //        .eq(dtsBatteryManage != null && !StringUtils.isEmpty(dtsBatteryManage.getElectricCabinetCode()),DtsBatteryManage::getElectricCabinetCode,dtsBatteryManage.getElectricCabinetCode())
        //        .eq(dtsBatteryManage != null && !StringUtils.isEmpty(dtsBatteryManage.getBatteryCode()),DtsBatteryManage::getBatteryCode,dtsBatteryManage.getBatteryCode())
        //);
    }

    @Override
    public boolean addDtsBatteryManage(DtsBatteryManage dtsBatteryManage) {
        dtsBatteryManage.setId(IdWorker.getId());
        dtsBatteryManage.setIsDelete((byte) 0);
        dtsBatteryManage.setStatus((byte) 1);
        //dtsBarManage.setCreateBy(SecurityUtils.getUserId());
        dtsBatteryManage.setCreated(new Date());
        List<String> batteryCodes = dtsBatteryManage.getBatteryCodes();
        //if (batteryCodes!=null){
        //
        //}
        return  save(dtsBatteryManage);

    }

    @Transactional
    @Override
    public boolean updateDtsBatteryManage(DtsBatteryManage dtsBatteryManage) {
        dtsBatteryManage.setCreated(new Date());
        DtsBatteryHistory dtsBatteryHistory = new DtsBatteryHistory();
        dtsBatteryHistory.setId(IdWorker.getId());
        dtsBatteryHistory.setBatteryId(dtsBatteryManage.getId());
        dtsBatteryHistory.setCreatedBattery(new Date());
        dtsBatteryHistory.setUpdated(new Date());
        dtsBatteryHistory.setStatus(dtsBatteryManage.getOutBound());
        dtsBatteryHistory.setHistoryState(dtsBatteryManage.getBatteryStatus());
        if (dtsBatteryManage.getElectricCabinetName() != null && dtsBatteryManage.getElectricCabinetCode()!=null){
            dtsBatteryHistory.setCellCode(dtsBatteryManage.getElectricCabinetCode());
            dtsBatteryHistory.setCellName(dtsBatteryManage.getElectricCabinetName());
        }
        dtsBatteryHistoryMapper.insert(dtsBatteryHistory);


        return updateById(dtsBatteryManage);
    }

    @Transactional(rollbackFor = Exception.class)
    public void importBattery(MultipartFile file) {
        log.error("【表格导入电柜,文件名称】: [{}]");
        ImportParams params = new ImportParams();
        //params.setTitleRows(1);//设置一级标题行为1行
        //params.setHeadRows(1);//设置header标题为1行
        List<DtsBatteryManage> dtsBatteryManageList = null;
        try {
            dtsBatteryManageList = ExcelImportUtil.importExcel(file.getInputStream(), DtsBatteryManage.class, params);
            System.out.println("【导入总数为】: [{}]" + dtsBatteryManageList.size());
            if (CollectionUtils.isEmpty(dtsBatteryManageList)){
                throw new MyException("电柜表格不能为空");
            }else {
                for (DtsBatteryManage dtsBatteryManage : dtsBatteryManageList) {
                    dtsBatteryManage.setId(IdWorker.getId());
                    dtsBatteryManage.setCreated(new Date());
                    dtsBatteryManage.setIsDelete((byte) 0);
                }
            }
            saveBatch(dtsBatteryManageList);

        } catch (Exception e) {
            log.error("【表格导入失败】：");
            throw new MyException("表格导入失败");
        }

    }



    @Override
    public boolean saveBatterys(DtsBatteryManage dtsBatteryManage) {
        ArrayList<DtsBatteryManage> dtsBatteryManages = new ArrayList<>();//新增时
        ArrayList<DtsBatteryManage> updateBatteryManages = new ArrayList<>();//修改时
        List<String> batteryCodes = dtsBatteryManage.getBatteryCodes();
        if (batteryCodes == null){
            throw new MyException("请检查填入的数据是否有误");
        }

        //替换时
        if (dtsBatteryManage.getBatteryStatus() == 1630111661320654855l && batteryCodes.size()%2 == 0){
            DtsBatteryManage dtsBatteryManage1 = new DtsBatteryManage();
            dtsBatteryManage1.setId(IdWorker.getId());
            dtsBatteryManage1.setIsDelete((byte) 0);
            dtsBatteryManage1.setCreated(new Date());
            dtsBatteryManage1.setBatteryCode(batteryCodes.get(0));
            dtsBatteryManage1.setElectricCabinetCode(dtsBatteryManage.getElectricCabinetCode());
            dtsBatteryManage1.setElectricCabinetName(dtsBatteryManage.getElectricCabinetName());
            dtsBatteryManage1.setOutBound(dtsBatteryManage.getOutBound());
            dtsBatteryManage1.setBatteryStatus(dtsBatteryManage.getBatteryStatus());
            dtsBatteryManage1.setRemark(dtsBatteryManage.getRemark());
            dtsBatteryManage1.setBatteryCodeOld(batteryCodes.get(1));
            dtsBatteryManages.add(dtsBatteryManage1);
            }else {
            //其他状态时
            for (String batteryCode : batteryCodes) {
                DtsBatteryManage batteryManage = getOne(new LambdaQueryWrapper<DtsBatteryManage>()
                        .eq(dtsBatteryManage != null && !StringUtils.isEmpty(dtsBatteryManage.getElectricCabinetCode()),DtsBatteryManage::getElectricCabinetCode, dtsBatteryManage.getElectricCabinetCode())
                        .eq(DtsBatteryManage::getBatteryCode, batteryCode));

                if (batteryManage != null && !StringUtils.isEmpty(dtsBatteryManage.getElectricCabinetCode())) {
                    throw new MyException("此电池" + batteryManage.getBatteryCode() + "已被电柜占用");
                }

                if ( StringUtils.isEmpty(dtsBatteryManage.getElectricCabinetCode()) && batteryManage!= null && batteryManage.getBatteryStatus() == dtsBatteryManage.getBatteryStatus()
                        && batteryManage.getOutBound() == dtsBatteryManage.getOutBound()){
                    throw new MyException("此电池" + batteryManage.getBatteryCode() + "已存在,请勿重复添加");
                }

                // 更新状态
                if ( StringUtils.isEmpty(dtsBatteryManage.getElectricCabinetCode()) && batteryManage!= null && batteryManage.getBatteryStatus() != dtsBatteryManage.getBatteryStatus()
                        && batteryManage.getOutBound() != dtsBatteryManage.getOutBound()){//更新
                   batteryManage.setBatteryStatus(dtsBatteryManage.getBatteryStatus());
                   batteryManage.setOutBound(dtsBatteryManage.getOutBound());

                    //DtsBatteryHistory dtsBatteryHistory = new DtsBatteryHistory();
                    //dtsBatteryHistory.setId(IdWorker.getId());
                    //dtsBatteryHistory.setBatteryId(dtsBatteryManage.getId());
                    //dtsBatteryHistory.setCreatedBattery(new Date());
                    //dtsBatteryHistory.setUpdated(new Date());
                    //dtsBatteryHistory.setStatus(dtsBatteryManage.getOutBound());
                    //dtsBatteryHistory.setHistoryState(dtsBatteryManage.getBatteryStatus());
                    //if (dtsBatteryManage.getElectricCabinetName() != null && dtsBatteryManage.getElectricCabinetCode()!=null){
                    //    dtsBatteryHistory.setCellCode(dtsBatteryManage.getElectricCabinetCode());
                    //    dtsBatteryHistory.setCellName(dtsBatteryManage.getElectricCabinetName());
                    //}
                    //dtsBatteryHistoryMapper.insert(dtsBatteryHistory);


                    updateBatteryManages.add(batteryManage);
                    updateBatchById(updateBatteryManages);
                    throw new MyException("此电池" + batteryManage.getBatteryCode() + "改变用途成功");
                   //return updateById(batteryManage); updateBatteryManages

                }

                DtsBatteryManage dtsBatteryManage1 = new DtsBatteryManage();
                dtsBatteryManage1.setId(IdWorker.getId());
                dtsBatteryManage1.setIsDelete((byte) 0);
                dtsBatteryManage1.setCreated(new Date());
                dtsBatteryManage1.setBatteryCode(batteryCode);
                dtsBatteryManage1.setElectricCabinetCode(dtsBatteryManage.getElectricCabinetCode());
                dtsBatteryManage1.setElectricCabinetName(dtsBatteryManage.getElectricCabinetName());
                dtsBatteryManage1.setOutBound(dtsBatteryManage.getOutBound());
                dtsBatteryManage1.setBatteryStatus(dtsBatteryManage.getBatteryStatus());
                dtsBatteryManage1.setRemark(dtsBatteryManage.getRemark());
                dtsBatteryManage1.setBatteryCodeOld(dtsBatteryManage.getBatteryCodeOld());
                dtsBatteryManages.add(dtsBatteryManage1);
            }
        }

        return saveBatch(dtsBatteryManages);
    }

    @Transactional(rollbackFor = Exception.class)
    public void importRecharge(MultipartFile file) {
        log.error("【表格导入电池,文件名称】: [{}]");
        ImportParams params = new ImportParams();
        //params.setTitleRows(1);//设置一级标题行为1行
        //params.setHeadRows(1);//设置header标题为1行
        List<DtsBatteryManage> dtsBatteryManages = null;
        try {
            dtsBatteryManages = ExcelImportUtil.importExcel(file.getInputStream(), DtsBatteryManage.class, params);
            System.out.println("【导入总数为】: [{}]" + dtsBatteryManages.size());
            if (CollectionUtils.isEmpty(dtsBatteryManages)) {
                throw new MyException("电池表格不能为空");
            } else {
                for (DtsBatteryManage dtsBatteryManage : dtsBatteryManages) {
                    dtsBatteryManage.setId(IdWorker.getId());
                    dtsBatteryManage.setCreated(new Date());
                    dtsBatteryManage.setStatus((byte) 0);

                }
            }
            saveBatch(dtsBatteryManages);

        } catch (Exception e) {
            log.error("【表格导入失败】：");
            throw new MyException("表格导入失败");
        }

    }


    @Override
    public void exportBattery( HttpServletResponse response,String electricCabinetCode, Long batteryStatus,String electricCabinetName,
                               String batteryCode) {
        //List<DtsBatteryManage> dtsBatteryManages = list(new LambdaQueryWrapper<DtsBatteryManage>()
        //        .eq(DtsBatteryManage::getBatteryStatus,status)
        //        );
        List<DtsCellExcel> list = dtsBatteryManageMapper.getCellUse( electricCabinetCode,  batteryStatus, electricCabinetName,
                batteryCode);

        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(MyDateUtils.getCurMonth() + "电池用途明细", MyDateUtils.getCurMonth()), DtsCellExcel.class, list);

        try {
            response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(MyDateUtils.getCurMonth() + "电池用途明细.xls", "UTF-8"));
            ServletOutputStream os = response.getOutputStream();
            workbook.write(os);
            os.close();
            workbook.close();
        } catch (IOException e) {
            //log.error("【导出今月修复明细,错误】{}", JSON.toJSONString(e, true));
            log.error("【导出今日修复明细,错误】{}",e);
        }
    }

    @Override
    public boolean saveBatteryList(DtsBatteryManage dtsBatteryManage) {
        ArrayList<DtsBatteryManage> dtsBatteryManages = new ArrayList<>();//新增时
        ArrayList<DtsBatteryManage> dtsBatterylist = new ArrayList<>();//新增时
        ArrayList<DtsBatteryManage> updateBatteryManages = new ArrayList<>();//修改时
        List<String> batteryCodes = dtsBatteryManage.getBatteryCodes();
        if (batteryCodes == null && batteryCodes.size()  == 0){
            throw new MyException("请检查填入的数据是否有误");
        }
        for (String batteryCode : batteryCodes) {

            DtsBatteryManage batteryManage = getOne(new LambdaQueryWrapper<DtsBatteryManage>()
                    //.eq(dtsBatteryManage != null && !StringUtils.isEmpty(dtsBatteryManage.getElectricCabinetCode()), DtsBatteryManage::getElectricCabinetCode, dtsBatteryManage.getElectricCabinetCode())
                    .eq(DtsBatteryManage::getBatteryCode, batteryCode));


            if (batteryManage == null  && dtsBatteryManage.getBatteryStatus() != 1630111661320654855l ) {
                DtsBatteryManage dtsBatteryManage1 = new DtsBatteryManage();
                dtsBatteryManage1.setId(IdWorker.getId());
                dtsBatteryManage1.setIsDelete((byte) 0);
                dtsBatteryManage1.setCreated(new Date());
                dtsBatteryManage1.setBatteryCode(batteryCode);
                dtsBatteryManage1.setElectricCabinetCode(dtsBatteryManage.getElectricCabinetCode());
                dtsBatteryManage1.setElectricCabinetName(dtsBatteryManage.getElectricCabinetName());
                dtsBatteryManage1.setOutBound(dtsBatteryManage.getOutBound());
                dtsBatteryManage1.setBatteryStatus(dtsBatteryManage.getBatteryStatus());
                dtsBatteryManage1.setRemark(dtsBatteryManage.getRemark());
                dtsBatteryManage1.setBatteryCodeOld(dtsBatteryManage.getBatteryCodeOld());
                //chalishi

                dtsBatteryManages.add(dtsBatteryManage1);//新增

            } else {

            //if (batteryManage != null && !StringUtils.isEmpty(batteryManage.getElectricCabinetCode())) {
            //    throw new MyException("此电池" + batteryManage.getBatteryCode() + "已被" + batteryManage.getElectricCabinetCode() + "电柜占用");
            //}

            if (dtsBatteryManage.getBatteryStatus() == 1630111661320654855l && batteryCodes.size() % 2 == 0) {
                DtsBatteryManage dtsBatteryManage1 = new DtsBatteryManage();
                dtsBatteryManage1.setId(IdWorker.getId());
                dtsBatteryManage1.setIsDelete((byte) 0);
                dtsBatteryManage1.setCreated(new Date());
                dtsBatteryManage1.setBatteryCode(batteryCodes.get(0));
                dtsBatteryManage1.setElectricCabinetCode(dtsBatteryManage.getElectricCabinetCode());
                dtsBatteryManage1.setElectricCabinetName(dtsBatteryManage.getElectricCabinetName());
                dtsBatteryManage1.setOutBound(dtsBatteryManage.getOutBound());
                dtsBatteryManage1.setBatteryStatus(dtsBatteryManage.getBatteryStatus());
                dtsBatteryManage1.setRemark(dtsBatteryManage.getRemark());
                dtsBatteryManage1.setBatteryCodeOld(batteryCodes.get(1));

                dtsBatterylist.add(dtsBatteryManage1);

            }

            if (  batteryManage != null && batteryManage.getBatteryStatus().equals(dtsBatteryManage.getBatteryStatus())
                    && batteryManage.getOutBound().equals(dtsBatteryManage.getOutBound()) ) {
                throw new MyException("此电池" + batteryManage.getBatteryCode() + "已存在,请勿重复添加");
            }

            // 更新状态
            if ( batteryManage != null && batteryManage.getBatteryStatus() != dtsBatteryManage.getBatteryStatus()) {//更新
                batteryManage.setBatteryStatus(dtsBatteryManage.getBatteryStatus());
                batteryManage.setOutBound(dtsBatteryManage.getOutBound());
                batteryManage.setRemark(dtsBatteryManage.getRemark());
                batteryManage.setCreated(new Date());
                DtsBatteryHistory dtsBatteryHistory = new DtsBatteryHistory();
                dtsBatteryHistory.setId(IdWorker.getId());
                //dtsBatteryHistory.setBatteryId(dtsBatteryManage.getId());
                dtsBatteryHistory.setBatteryId(batteryManage.getId());
                //dtsBatteryHistory.setBatteryCode(dtsBatteryManage.getBatteryCode());
                dtsBatteryHistory.setCreatedBattery(new Date());
                dtsBatteryHistory.setUpdated(new Date());
                dtsBatteryHistory.setStatus(dtsBatteryManage.getOutBound());
                dtsBatteryHistory.setHistoryState(dtsBatteryManage.getBatteryStatus());
                if (dtsBatteryManage.getElectricCabinetName() != null && dtsBatteryManage.getElectricCabinetCode() != null) {
                    batteryManage.setElectricCabinetName(dtsBatteryManage.getElectricCabinetName());
                    batteryManage.setElectricCabinetCode(dtsBatteryManage.getElectricCabinetCode());
                    dtsBatteryHistory.setCellCode(dtsBatteryManage.getElectricCabinetCode());
                    dtsBatteryHistory.setCellName(dtsBatteryManage.getElectricCabinetName());
                }
                dtsBatteryHistoryMapper.insert(dtsBatteryHistory);


                updateBatteryManages.add(batteryManage);

                //throw new MyException("此电池" + batteryManage.getBatteryCode() + "改变用途成功");
                //return updateById(batteryManage); updateBatteryManages

            }

        }
        }

        if (dtsBatterylist != null && dtsBatterylist.size() > 0) {
            List<DtsBatteryManage> list1 = dtsBatterylist.stream().collect(
                    Collectors.collectingAndThen(Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(p -> p.getBatteryCodeOld()+";"+p.getBatteryCode()))), ArrayList::new)
            );

                return saveBatch(list1);



        }
        if (dtsBatteryManages.size() >0  ) {
            //第一次插历史
            boolean b = insrtInfoHis(dtsBatteryManages, dtsBatteryManage);
            if (b) {
                return saveBatch(dtsBatteryManages);
            }


        }
        return  updateBatchById(updateBatteryManages);

    }


    public boolean  insrtInfoHis(ArrayList<DtsBatteryManage> dtsBatteryManages,DtsBatteryManage dtsBatteryManage){
        int insert = 0;
        for(DtsBatteryManage batteryManage : dtsBatteryManages) {
            DtsBatteryHistory dtsBatteryHistory = new DtsBatteryHistory();
            dtsBatteryHistory.setId(IdWorker.getId());
            //dtsBatteryHistory.setBatteryId(dtsBatteryManage.getId());
            dtsBatteryHistory.setBatteryId(batteryManage.getId());
            //dtsBatteryHistory.setBatteryCode(dtsBatteryManage.getBatteryCode());
            dtsBatteryHistory.setCreatedBattery(new Date());
            dtsBatteryHistory.setUpdated(new Date());
            dtsBatteryHistory.setStatus(dtsBatteryManage.getOutBound());
            dtsBatteryHistory.setHistoryState(dtsBatteryManage.getBatteryStatus());
            dtsBatteryHistory.setCellCode(dtsBatteryManage.getElectricCabinetCode());
            dtsBatteryHistory.setCellName(dtsBatteryManage.getElectricCabinetName());
            insert += dtsBatteryHistoryMapper.insert(dtsBatteryHistory);
        }
        if (insert < 0){
            return  false;
        }
        return true;
    }

    public boolean  insrtInfoHisRepace(ArrayList<DtsBatteryManage> dtsBatteryManages,DtsBatteryManage dtsBatteryManage){
        int insert = 0;
        for(DtsBatteryManage batteryManage : dtsBatteryManages) {
            DtsBatteryHistory dtsBatteryHistory = new DtsBatteryHistory();
            dtsBatteryHistory.setId(IdWorker.getId());
            //dtsBatteryHistory.setBatteryId(dtsBatteryManage.getId());
            dtsBatteryHistory.setBatteryId(batteryManage.getId());
            //dtsBatteryHistory.setBatteryCode(dtsBatteryManage.getBatteryCode());
            dtsBatteryHistory.setCreatedBattery(new Date());
            dtsBatteryHistory.setUpdated(new Date());
            dtsBatteryHistory.setStatus(dtsBatteryManage.getOutBound());
            dtsBatteryHistory.setHistoryState(dtsBatteryManage.getBatteryStatus());
            dtsBatteryHistory.setCellCode(dtsBatteryManage.getElectricCabinetCode());
            dtsBatteryHistory.setCellName(dtsBatteryManage.getElectricCabinetName());
            insert += dtsBatteryHistoryMapper.insert(dtsBatteryHistory);
        }
        if (insert < 0){
            return  false;
        }
        return true;
    }
}
